﻿using DataLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Common;
using System.Collections;

namespace TicketSystem
{
    public partial class UC_Ticket : UserControl
    {
        private TicketSystemEntities tse = new TicketSystemEntities();
        private int _flag = 0;
        private string _errMsg = "";
        private int _departmentid = 0;
        private string _LastPurchaseMoney = "";
        private string _LastSignedNumber = "";
        private int lastsaleid = 0;
        
        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi)]
        internal static extern IntPtr GetFocus();
        public UC_Ticket()
        {
            InitializeComponent();            
        }

        private Control GetFoucsedControl()
        {
            Control foucsed = null;
            IntPtr foucsedHandle = GetFocus();
            if (foucsedHandle != IntPtr.Zero)
                foucsed = Control.FromChildHandle(foucsedHandle);
            return foucsed;            
        }

        private void Select_Content()
        {
            Control _control = GetFoucsedControl();
            if (_control.Name == "checkBox_Sign" || _control.Name.Contains("Number") && !_control.Name.Contains("Signed") && !string.IsNullOrEmpty(_control.Text))
            {
                SendKeys.Send("{HOME}+{END}");
            }
        }
        private void txt_Number_Enter(object sender, EventArgs e)
        {
            Select_Content();
        }

        //回车事件1（保存）
        private void PressEnter_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.btn_Save_Click(sender, e);
            }
        }
        //回车事件2（下一个）
        private void PressEnter2_KeyDown(object sender, KeyEventArgs e)
        {            
            if (e.KeyCode == Keys.Enter)
            {
                System.Windows.Forms.SendKeys.Send("{TAB}");
            }
            Control control = GetFoucsedControl();
            if (control.Name == "checkBox_Sign")
            {
                ResetTicketData();
            }
        }
        private void ResetGuideData() 
        {
            txt_GuideIDCard.Text = "";
            txt_GuideName.Text = "";
            txt_GuidePhone.Text = "";
            cBox_GuideCardNum.Text = "";
            cBox_Department.Text = "";
            txt_DepartPhone.Text = "";
            cBox_GuideCardNum.Focus();
        }
        private void ResetTicketData()
        {            
            txt_SignedPeople.Text = "";
            txt_ParkSpecialNumber.Text = "";
            txt_ParkAdultNumber.Text = "";
            txt_ThreeNumber.Text = "";
            txt_TwoNumber.Text = "";
            txt_OneNumber.Text = "";
            txt_OneSpecialNumber.Text = "";
            txt_SignedNumber.Text = "";
            txt_PurchaseMoney.Text = "";
            cBox_PayStyle.Text = "普通支付";            
        }
        private void InitData()
        {
            var TicketInfo = (from n in tse.TicketTypes select new { n.TypeID, n.Name, n.Price, n.SpecialPrice, n.Created_at, n.Updated_at }).ToList();
            dGrid_TIckitInfo.DataSource = TicketInfo;
            //修改表头
            dGrid_TIckitInfo.Columns[0].HeaderCell.Value = "ID"; dGrid_TIckitInfo.Columns[1].HeaderCell.Value = "票种"; dGrid_TIckitInfo.Columns[2].HeaderCell.Value = "票价"; dGrid_TIckitInfo.Columns[3].HeaderCell.Value = "特价票"; dGrid_TIckitInfo.Columns[4].HeaderCell.Value = "创建时间"; dGrid_TIckitInfo.Columns[5].HeaderCell.Value = "修改时间";
            //部门信息
            var departments = tse.Departments.Select(u => u.DepartmentName).ToList();
            //cBox_Department.DataSource = departments;
            cBox_Department.Text = "";
            //导游信息
            var GuideIDList = tse.Guides.Select(u => u.GuideCard).ToList();
            //cBox_GuideCardNum.DataSource = GuideIDList;
            //自动补全导游编号和部门信息
            var source = new AutoCompleteStringCollection();
            var source2 = new AutoCompleteStringCollection();
            foreach (var id in GuideIDList)
            {
                source.Add(id.Trim());
            }
            foreach (var department in departments)
            {
                source2.Add(department.Trim());
            }
            cBox_GuideCardNum.AutoCompleteCustomSource = source;
            cBox_GuideCardNum.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            cBox_GuideCardNum.AutoCompleteSource = AutoCompleteSource.CustomSource;
            txt_GuideIDCard.Text = ""; txt_GuideName.Text = ""; txt_GuidePhone.Text = ""; cBox_GuideCardNum.Text = "";
            cBox_Department.AutoCompleteCustomSource = source2;
            cBox_Department.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            cBox_Department.AutoCompleteSource = AutoCompleteSource.CustomSource;
            cBox_Department.Text = "";
            //各类门票信息
            //txt_OnePrice.Text = Math.Round(TicketInfo.Find(u => u.TypeID == 1).Price,2).ToString();
            //txt_OneSpecialPrice.Text = Math.Round(TicketInfo.Find(u => u.TypeID == 1).Price,2).ToString();
            //txt_TwoPrice.Text = Math.Round(TicketInfo.Find(u => u.TypeID == 2).Price,2).ToString();
            //txt_ThreePrice.Text = Math.Round(TicketInfo.Find(u => u.TypeID == 3).Price,2).ToString();
            //var parkPrices = TicketInfo.Find(u => u.TypeID == 4);
            //txt_ParkAdultPrice.Text = Math.Round(parkPrices.Price,2).ToString();
            //txt_ParkSpecialPrice.Text = Math.Round(parkPrices.SpecialPrice,2).ToString();
            txt_OnePrice.Text = Price.PriceOne.ToString();
            txt_OneSpecialPrice.Text = Price.PriceOne.ToString();
            txt_TwoPrice.Text = Price.PriceTwo.ToString();
            txt_ThreePrice.Text = Price.PriceThree.ToString();            
            txt_ParkAdultPrice.Text = Price.PriceParkAdult.ToString();
            txt_ParkSpecialPrice.Text = Price.PriceParkSpecial.ToString();
            txt_SignedPeople.Text = "0";
            txt_SignedPeople.Enabled = false;//部门不可填
            cBox_PayStyle.Text = "普通支付";
            txt_DepartPhone.Text = "";
        }
        private void Ticket_Load(object sender, EventArgs e)
        {
            InitData();
            List<String> list = Common.PrintDataGridView.GetLocalPrinters(); //获得系统中的打印机列表
            foreach (String s in list)
            {
                if (s.ToUpper().Contains("EPSON"))
                {
                    Common.Externs.SetDefaultPrinter(s);
                    break;
                }
            }
            lastsaleid = tse.Sales.OrderByDescending(u => u.SaleID).First().SaleID;//获取id
        }
        
        #region
        private string getSubTotle(string num, string price)
        {
            if (!string.IsNullOrEmpty(num))
            {
                try
                {
                    if (int.Parse(num) > 0)
                        return Math.Round((decimal.Parse(num) * decimal.Parse(price)),2).ToString();
                    else
                        return "0";
                }
                catch
                {
                    MessageBox.Show("请输入非负的整数");
                    return "0";
                }
            }
            else
                return "0";
        }
        private string getPurchaselMoney()
        {
            List<string> list = new List<string>();
            if (!checkBox_Sign.Checked)
            {
                list.Add(txt_OneTotle.Text);
            }
            list.Add(txt_TwoTotle.Text);
            list.Add(txt_ThreeTotle.Text);
            list.Add(txt_ParkTotle.Text);
            decimal Total = 0;
            foreach (string l in list)
            {
                if (!string.IsNullOrEmpty(l))
                    Total += decimal.Parse(l);
            }
            return Math.Round(Total, 2).ToString();
        }
        //签单人数变化
        private void txt_SignedPeople_TextChanged(object sender, EventArgs e)
        {
            txt_SignedNumber.Text = "";
            int signedPeople = string.IsNullOrEmpty(txt_SignedPeople.Text) ? 0 : int.Parse(txt_SignedPeople.Text);
            int one = string.IsNullOrEmpty(txt_OneNumber.Text) ? 0 : int.Parse(txt_OneNumber.Text);
            int onespecial = string.IsNullOrEmpty(txt_OneSpecialNumber.Text) ? 0 : int.Parse(txt_OneSpecialNumber.Text);
            if(signedPeople > (one+onespecial))
            {
                MessageBox.Show("签单人数不得超过首套船人数");
                txt_SignedPeople.Text = (one + onespecial).ToString();
                return;
            }
            decimal signedMoney = decimal.Parse(txt_OnePrice.Text) * signedPeople;
            decimal total = decimal.Parse(getPurchaselMoney());
            //txt_PurchaseMoney.Text = (total - signedMoney).ToString();
            txt_PurchaseMoney.Text = Math.Round(total,2).ToString();
        }

        //首套船
        private void txt_OneNumber_TextChanged(object sender, EventArgs e)
        {
            txt_OneSubTotle.Text = getSubTotle(txt_OneNumber.Text, txt_OnePrice.Text);
            txt_OneTotle.Text = "0";
            decimal oneTotal = string.IsNullOrEmpty(txt_OneNumber.Text) ? 0 : decimal.Parse(txt_OneSubTotle.Text);
            decimal oneSpecialTotal = string.IsNullOrEmpty(txt_OneSpecialNumber.Text) ? 0 : decimal.Parse(txt_OneSpecialSubTotle.Text);
            txt_OneTotle.Text = (oneTotal + oneSpecialTotal).ToString();
            txt_PurchaseMoney.Text = getPurchaselMoney();
            //check();
            if (checkBox_Sign.Checked)
            {
                int one = string.IsNullOrEmpty(txt_OneNumber.Text) ? 0 : int.Parse(txt_OneNumber.Text);
                int oneSpecial = string.IsNullOrEmpty(txt_OneSpecialNumber.Text) ? 0 : int.Parse(txt_OneSpecialNumber.Text);
                txt_SignedPeople.Text = (one + oneSpecial).ToString();
            }
        }
        //首道船特价票
        private void txt_OneSpecialNumber_TextChanged(object sender, EventArgs e)
        {
            txt_OneSpecialSubTotle.Text = getSubTotle(txt_OneSpecialNumber.Text, txt_OneSpecialPrice.Text);
            //txt_OneTotle.Text = txt_OneSpecialSubTotle.Text;
            //txt_PurchaseMoney.Text = getPurchaselMoney();
            if (!string.IsNullOrEmpty(txt_OneSpecialNumber.Text))
                txt_OneTotle.Text = txt_OneSpecialSubTotle.Text;
            if (!string.IsNullOrEmpty(txt_OneNumber.Text))
                txt_OneTotle.Text = Math.Round(decimal.Parse(txt_OneSubTotle.Text) + decimal.Parse(txt_OneSpecialSubTotle.Text),2).ToString();
            txt_PurchaseMoney.Text = getPurchaselMoney();
            //check();
            if (checkBox_Sign.Checked)
            {
                int one = string.IsNullOrEmpty(txt_OneNumber.Text) ? 0 : int.Parse(txt_OneNumber.Text);
                int oneSpecial = string.IsNullOrEmpty(txt_OneSpecialNumber.Text) ? 0 : int.Parse(txt_OneSpecialNumber.Text);
                txt_SignedPeople.Text = (one + oneSpecial).ToString();
            }
        }
        //公园成人票
        private void txt_ParkAdultNum_TextChanged(object sender, EventArgs e)
        {
            txt_ParkAdultSubTotle.Text = getSubTotle(txt_ParkAdultNumber.Text, txt_ParkAdultPrice.Text);
            txt_ParkTotle.Text = "0";
            decimal parkTotal = string.IsNullOrEmpty(txt_ParkAdultNumber.Text) ? 0 : decimal.Parse(txt_ParkAdultSubTotle.Text);
            decimal parkSepecialTotal = string.IsNullOrEmpty(txt_ParkSpecialNumber.Text) ? 0 : decimal.Parse(txt_ParkSpecialSubTotle.Text);
            txt_ParkTotle.Text = (parkTotal + parkSepecialTotal).ToString();
            txt_PurchaseMoney.Text = getPurchaselMoney();
            //check();
        }
        //公园特价票
        private void txt_ParkSpecialNum_TextChanged(object sender, EventArgs e)
        {
            txt_ParkSpecialSubTotle.Text = getSubTotle(txt_ParkSpecialNumber.Text, txt_ParkSpecialPrice.Text);
            if (!string.IsNullOrEmpty(txt_ParkSpecialNumber.Text))
                txt_ParkTotle.Text = txt_ParkSpecialSubTotle.Text;
            if (!string.IsNullOrEmpty(txt_ParkAdultNumber.Text))
                txt_ParkTotle.Text = (decimal.Parse(txt_ParkAdultSubTotle.Text) + decimal.Parse(txt_ParkSpecialSubTotle.Text)).ToString();
            decimal parkTotal = string.IsNullOrEmpty(txt_ParkAdultNumber.Text) ? 0 : decimal.Parse(txt_ParkAdultSubTotle.Text);
            decimal parkSepecialTotal = string.IsNullOrEmpty(txt_ParkSpecialNumber.Text) ? 0 : decimal.Parse(txt_ParkSpecialSubTotle.Text);
            txt_ParkTotle.Text = (parkTotal + parkSepecialTotal).ToString();
            txt_PurchaseMoney.Text = getPurchaselMoney();
            //check();
        }
        //二道船（颐内船）
        private void txt_TwoNumber_TextChanged(object sender, EventArgs e)
        {
            txt_TwoSubTotle.Text = getSubTotle(txt_TwoNumber.Text, txt_TwoPrice.Text);
            txt_TwoTotle.Text = txt_TwoSubTotle.Text;
            txt_PurchaseMoney.Text = getPurchaselMoney();
        }
        //三道船（颐内船）
        private void txt_ThreeNumber_TextChanged(object sender, EventArgs e)
        {
            txt_ThreeSubTotle.Text = getSubTotle(txt_ThreeNumber.Text, txt_ThreePrice.Text);
            txt_ThreeTotle.Text = txt_ThreeSubTotle.Text;
            txt_PurchaseMoney.Text = getPurchaselMoney();
        }

        private int check()
        {
            int one = string.IsNullOrEmpty(txt_OneNumber.Text) ? 0 : int.Parse(txt_OneNumber.Text);
            int onespecial = string.IsNullOrEmpty(txt_OneSpecialNumber.Text) ? 0 : int.Parse(txt_OneSpecialNumber.Text);
            int park = string.IsNullOrEmpty(txt_ParkAdultNumber.Text) ? 0 : int.Parse(txt_ParkAdultNumber.Text);
            int special = string.IsNullOrEmpty(txt_ParkSpecialNumber.Text) ? 0 : int.Parse(txt_ParkSpecialNumber.Text);
            if (park > (one + onespecial) || special > (one + onespecial) || (park + special) > (one + onespecial))
            {
                _errMsg = "入园票人数不得多于首套船人数";
                _flag = -1;
            }
            else
                _flag = 0;            
            return _flag;
        }
        #endregion

        private void btn_SearchGuide_Click(object sender, EventArgs e)
        {
            string name = string.IsNullOrEmpty(txt_GuideName.Text) ? "" : txt_GuideName.Text;
            var guide = tse.Guides.Where(u => u.Name == name).ToList();
            if (guide != null && guide.Count == 1)
            {
                cBox_GuideCardNum.Text = guide.First().GuideCard.Trim();
                cBox_GuideCardNum.Focus();
            }
            else
            {
                //这里以后需要解决重名问题！！20161201
                MessageBox.Show("没有该导游或叫这个姓名的导游人数较多");
                txt_GuideIDCard.Text = "";
                txt_GuidePhone.Text = "";
                cBox_GuideCardNum.Text = "";
                cBox_Department.Text = "";
                txt_DepartPhone.Text = "";
            }
        }

        //卡号变化时的一些判定
        private void cBox_GuideID_Changed(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cBox_GuideCardNum.Text))
            {
                //先加载资源，后进行检索
                var departs = tse.Departments.Select(u => u.DepartmentName).ToList();
                var source = new AutoCompleteStringCollection();
                foreach (var d in departs)
                {
                    source.Add(d.Trim());
                }
                cBox_Department.DataSource = source;
                cBox_Department.AutoCompleteCustomSource = source;
                cBox_Department.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                cBox_Department.AutoCompleteSource = AutoCompleteSource.CustomSource;
                lb_GuideNotExist.Visible = false;
                try
                {
                    var guide = tse.Guides.FirstOrDefault(u => u.GuideCard == cBox_GuideCardNum.Text);
                    txt_GuideIDCard.Text = guide.IDCard.Trim(); txt_GuideIDCard.Enabled = false;
                    txt_GuidePhone.Text = guide.Phone.Trim(); 
                    //txt_GuidePhone.Enabled = false;                    
                    txt_GuideName.Text = guide.Name.Trim();
                    
                    cBox_Sex.Text = guide.Sex; 
                    cBox_Sex.Enabled = true;
                    if (guide.DepartmentsGuides1.Count() > 0)
                    {
                        cBox_Department.Text = string.IsNullOrEmpty(guide.DepartmentsGuides1.LastOrDefault().Departments.DepartmentName) ? "" : guide.DepartmentsGuides1.LastOrDefault().Departments.DepartmentName.Trim();
                        txt_DepartPhone.Text = string.IsNullOrEmpty(guide.DepartmentsGuides1.LastOrDefault().Departments.ContactNumber) ? "" : guide.DepartmentsGuides1.LastOrDefault().Departments.ContactNumber.Trim();                        
                    }
                }
                catch
                {
                    lb_GuideNotExist.Visible = true;
                    txt_GuideIDCard.Text = ""; txt_GuideIDCard.Enabled = true;
                    txt_GuidePhone.Text = ""; txt_GuidePhone.Enabled = true;
                    txt_GuideName.Text = "";
                    txt_DepartPhone.Text = "";
                    cBox_Department.Text = ""; cBox_Sex.Enabled = true;
                    return;
                }
            }
        }

        private void AddDepartAndGuide()
        {
            var guide = tse.Guides.Where(u => u.GuideCard == cBox_GuideCardNum.Text);
            if (guide.Count() > 0)
            {
                var depart_guide = guide.First().DepartmentsGuides1;
                if (depart_guide.Count > 0)
                {
                    bool flag = false;
                    foreach (var d in depart_guide)
                    {
                        if (d.Departments.DepartmentName.Trim() == cBox_Department.Text.Trim())
                        {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag)
                    {
                        var depart = tse.Departments.Where(u => u.DepartmentName == cBox_Department.Text);
                        if (depart.Count() > 0)
                        {
                            DepartmentsGuides _dg = new DepartmentsGuides();
                            _dg.DepartmentID = depart.FirstOrDefault().DepartmentID;
                            _dg.GuideID = guide.First().GuideID;
                            _dg.Created_at = DateTime.Now;
                            _dg.Updated_at = DateTime.Now;
                            tse.DepartmentsGuidesSet.Add(_dg);
                            tse.SaveChanges();
                        }
                        else
                        {
                            Departments _depart = new Departments();
                            _depart.DepartmentTypeID = 1;
                            _depart.DepartmentName = this.cBox_Department.Text;
                            _depart.AccountNumber = "";
                            _depart.Address = "";
                            _depart.Bank = "";
                            _depart.CanSign = 1;
                            _depart.ContactNumber = string.IsNullOrEmpty(txt_DepartPhone.Text) ? "" : txt_DepartPhone.Text;
                            _depart.DepartmentNickName = "";
                            _depart.Fax = "";
                            _depart.TaxNumber = "";
                            tse.Departments.Add(_depart);
                            tse.SaveChanges();
                            DepartmentsGuides _dg = new DepartmentsGuides();
                            _dg.DepartmentID = _depart.DepartmentID;
                            _dg.GuideID = guide.First().GuideID;
                            _dg.Created_at = DateTime.Now;
                            _dg.Updated_at = DateTime.Now;
                            tse.DepartmentsGuidesSet.Add(_dg);
                            tse.SaveChanges();
                            MessageBox.Show("未在系统中找到该旅行社信息，已自动将其信息添加至系统记录！");
                        }
                    }
                }
            }
            else
            {
                try
                {
                    Guides _guide = new Guides();
                    Departments _depart = new Departments();
                    DepartmentsGuides _dg = new DepartmentsGuides();
                    var depart = tse.Departments.Where(u => u.DepartmentName == cBox_Department.Text);
                    if (depart.Count() == 0)
                    {
                        _depart.DepartmentTypeID = 1;
                        _depart.DepartmentName = this.cBox_Department.Text;
                        _depart.AccountNumber = "";
                        _depart.Address = "";
                        _depart.Bank = "";
                        _depart.CanSign = 1;
                        _depart.ContactNumber = string.IsNullOrEmpty(txt_DepartPhone.Text) ? "" : txt_DepartPhone.Text;
                        _depart.DepartmentNickName = "";
                        _depart.Fax = "";
                        _depart.TaxNumber = "";
                        tse.Departments.Add(_depart);
                        tse.SaveChanges();
                    }
                    else
                    {
                        _depart = depart.FirstOrDefault();
                    }
                    _guide.GuideCard = cBox_GuideCardNum.Text;
                    _guide.Name = txt_GuideName.Text;
                    _guide.Sex = cBox_Sex.Text;
                    _guide.IDCard = txt_GuideIDCard.Text;
                    _guide.Phone = txt_GuidePhone.Text;
                    _guide.DepartmentID = tse.Departments.FirstOrDefault(u => u.DepartmentName == _depart.DepartmentName).DepartmentID;
                    _guide.NickName = ""; _guide.Picture = "";
                    tse.Guides.Add(_guide);
                    tse.SaveChanges();
                    _dg.DepartmentID = _depart.DepartmentID;
                    _dg.GuideID = _guide.GuideID;
                    _dg.Created_at = DateTime.Now;
                    _dg.Updated_at = DateTime.Now;
                    tse.DepartmentsGuidesSet.Add(_dg);
                    tse.SaveChanges();
                    MessageBox.Show("未在系统中找到该导游信息，已自动将其信息添加至系统记录！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            #region 保存打印前需要填写的必要信息
            if (string.IsNullOrEmpty(cBox_GuideCardNum.Text))
            {
                MessageBox.Show("导游卡号不可为空");
                return;
            }
            if (string.IsNullOrEmpty(txt_GuideName.Text))
            {
                MessageBox.Show("导游姓名不可为空");
                return;
            }
            if (string.IsNullOrEmpty(txt_GuidePhone.Text))
            {
                MessageBox.Show("导游电话不可为空");
                return;
            }
            if (string.IsNullOrEmpty(cBox_Department.Text))
            {
                MessageBox.Show("旅行社信息不可为空");
                return;
            }
            if (string.IsNullOrEmpty(txt_PurchaseMoney.Text) && (string.IsNullOrEmpty(txt_SignedPeople.Text)))
            {

                MessageBox.Show("尚未选择任何门票");
                return;
            }
            
            if (_flag < 0)
            {
                MessageBox.Show(_errMsg);
                return;
            }
            AddDepartAndGuide();

            #endregion
            //保存订单信息
            Sales sale = new Sales();
            //sale.DGID = tse.Guides.ToList().Find(u => u.GuideCard == cBox_GuideCardNum.Text).GuideID;
            int guideid = tse.Guides.Where(u => u.GuideCard == cBox_GuideCardNum.Text.Trim()).FirstOrDefault().GuideID;
            int departid = tse.Departments.Where(u => u.DepartmentName == cBox_Department.Text.Trim()).First().DepartmentID;
            var dg = tse.DepartmentsGuidesSet.Where(u => u.DepartmentID == departid && u.GuideID == guideid);
            if (dg.Count() == 0)
            {
                DepartmentsGuides _dg = new DepartmentsGuides();
                _dg.GuideID = guideid;
                _dg.DepartmentID = departid;
                _dg.Created_at = DateTime.Now;
                _dg.Updated_at = DateTime.Now;
                tse.DepartmentsGuidesSet.Add(_dg);
                tse.SaveChanges();
            }
            int dgid = tse.DepartmentsGuidesSet.Where(u => u.DepartmentID == departid && u.GuideID == guideid).First().DGID;
            sale.DGID = dgid;
            sale.OperatorID = GetOperator.OperatorID;
            sale.SaleGuid = Guid.NewGuid();
            //sale.PayStyle = 1;//默认普通支付
            sale.PayStyle = cBox_PayStyle.SelectedIndex + 1;
            decimal signed = 0;
            if (!string.IsNullOrEmpty(txt_SignedPeople.Text))
            {
                signed = decimal.Parse(txt_SignedPeople.Text);
            }
            sale.SignedMoney = signed * decimal.Parse(txt_OnePrice.Text);
            sale.SignedPeople = string.IsNullOrEmpty(txt_SignedPeople.Text) ? 0 : int.Parse(txt_SignedPeople.Text);
            sale.SignedNumber = string.IsNullOrEmpty(txt_SignedNumber.Text) ? "" : txt_SignedNumber.Text;
            sale.TicketOne = (string.IsNullOrEmpty(txt_OneNumber.Text) ? 0 : int.Parse(txt_OneNumber.Text)) + (string.IsNullOrEmpty(txt_OneSpecialNumber.Text) ? 0 : int.Parse(txt_OneSpecialNumber.Text));
            sale.TicketTwo = string.IsNullOrEmpty(txt_TwoNumber.Text) ? 0 : int.Parse(txt_TwoNumber.Text);
            sale.TicketThree = string.IsNullOrEmpty(txt_ThreeNumber.Text) ? 0 : int.Parse(txt_ThreeNumber.Text);
            sale.TicketPark = string.IsNullOrEmpty(txt_ParkAdultNumber.Text) ? 0 : int.Parse(txt_ParkAdultNumber.Text);
            sale.TicketParkSpecial = string.IsNullOrEmpty(txt_ParkSpecialNumber.Text) ? 0 : int.Parse(txt_ParkSpecialNumber.Text);
            sale.PurchaseMoney = string.IsNullOrEmpty(txt_PurchaseMoney.Text) ? 0 : decimal.Parse(txt_PurchaseMoney.Text);
            //sale.DepartmentID = tse.Departments.Where(u => u.DepartmentName == cBox_Department.Text).FirstOrDefault().DepartmentID;
            sale.BackFlag = 0;
            //sale.UnSignedMoney = decimal.Parse(txt_SignedNumber.Text);
            sale.Created_at = DateTime.Now;
            if (signed > 0 && (string.IsNullOrEmpty(txt_SignedNumber.Text) || txt_SignedNumber.Text == "0"))
            {
                MessageBox.Show("请输入签单号");
                txt_SignedNumber.Focus();
                return;
            }
            if (signed == 0 && (txt_SignedNumber.Text.Length >= 1))
            {
                txt_SignedNumber.Text = "";
                sale.SignedNumber = "";
                MessageBox.Show("检测到该订单没有签单人数，却填写了签单号，已将其置空");
            }
            if (tse.Checkouts.Count() > 0)
            {
                var _checkout = tse.Checkouts.OrderByDescending(u => u.CheckoutID).FirstOrDefault();
                if (_checkout.Checkout_at.Date == DateTime.Now.Date)//如果结账后则结账日为下一天
                {
                    sale.Checkout_at = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd ") + " 00:00:01");
                }
                else
                {
                    sale.Checkout_at = sale.Created_at;
                }
            }
            else
            {
                sale.Checkout_at = sale.Created_at;
            }
            //int lastsaleid = 1;
            //if (tse.Sales.Count() > 0)
            //{
            //    lastsaleid = tse.Sales.OrderByDescending(u => u.SaleID).First().SaleID;
            //}
            //sale.SaleID = lastsaleid + 1;
            //int lastsaleid = tse.Sales.OrderByDescending(u => u.SaleID).First().SaleID;
            
            sale.SaleID = lastsaleid + 1;
            DialogResult dresult = MessageBox.Show("请确认以下出票信息\r\n出票时间：" + DateTime.Now + "\r\n购票导游：" + txt_GuideName.Text + "\r\n旅行社：" + cBox_Department.Text + "\r\n首道船：" + txt_OneNumber.Text + "张\r\n首道船学生票" + txt_OneSpecialNumber.Text + "张\r\n进园成人票：" + txt_ParkAdultNumber.Text + "张\r\n进园学生票：" + txt_ParkSpecialNumber.Text + "张\r\n颐内一道船：" + txt_TwoNumber.Text + "张\r\n颐内二道船：" + txt_ThreeNumber.Text + "张", "确认出票", MessageBoxButtons.OKCancel);
            if (dresult == DialogResult.OK)
            {
                try
                {
                    lock (this)
                    {
                        tse.Sales.Add(sale);
                        tse.SaveChanges();
                        lastsaleid = sale.SaleID;
                        PrintDoc pd = new PrintDoc();
                        System.Drawing.Image _img = pd.CreateQuickMark(sale.SaleGuid.ToString());
                        string operatorName = tse.Operators.Find(sale.OperatorID).Name;
                        if (!string.IsNullOrEmpty(txt_OneNumber.Text) || !string.IsNullOrEmpty(txt_OneSpecialNumber.Text))
                        {
                            this.printDocument1.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("复写", 950, 367);
                            pd = print("一道船", "万寿寺", _img, sale.SaleID.ToString(), cBox_Department.Text, txt_GuideName.Text, sale.TicketOne, string.IsNullOrEmpty(txt_OneNumber.Text) ? 0 : int.Parse(txt_OneNumber.Text), string.IsNullOrEmpty(txt_OneSpecialNumber.Text) ? 0 : int.Parse(txt_OneSpecialNumber.Text), operatorName);
                            this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(pd.MyPrintDocument);
                            printPreviewDialog1.Document = printDocument1; //将写好的格式给打印预览控件以便预览   
                        }
                        if (!string.IsNullOrEmpty(txt_ParkAdultNumber.Text) || !string.IsNullOrEmpty(txt_ParkSpecialNumber.Text))
                        {
                            this.printDocument2.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("复写", 950, 367);
                            pd = print("进园票", "万寿寺", _img, sale.SaleID.ToString(), cBox_Department.Text, txt_GuideName.Text, sale.TicketPark + sale.TicketParkSpecial, sale.TicketPark, sale.TicketParkSpecial, operatorName);
                            this.printDocument2.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(pd.MyPrintDocument);
                            printPreviewDialog2.Document = printDocument2;
                        }
                        if (!string.IsNullOrEmpty(txt_TwoNumber.Text))
                        {
                            this.printDocument3.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("复写", 950, 367);
                            pd = print("二道船", "颐和园", _img, "", cBox_Department.Text, txt_GuideName.Text, sale.TicketTwo, sale.TicketTwo, 0, operatorName);
                            this.printDocument3.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(pd.MyPrintDocument);
                            printPreviewDialog3.Document = printDocument3;
                        }
                        if (!string.IsNullOrEmpty(txt_ThreeNumber.Text))
                        {
                            this.printDocument4.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("复写", 950, 367);
                            pd = print("3道船", "颐和园", _img, "", cBox_Department.Text, txt_GuideName.Text, sale.TicketThree, sale.TicketThree, 0, operatorName);
                            this.printDocument4.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(pd.MyPrintDocument);
                            printPreviewDialog4.Document = printDocument4;
                        }
                        MessageBoxButtons mb = MessageBoxButtons.YesNo;
                        DialogResult dr = MessageBox.Show(DateTime.Now + "，保存成功，是否打印?", "立即打印", mb);
                        if (dr == DialogResult.Yes)
                        {
                            //Common.Externs.SetDefaultPrinter()
                            if (checkBox_Preview.Checked)//显示打印预览
                            {
                                if (printPreviewDialog1.Document != null)
                                {
                                    DialogResult result1 = printPreviewDialog1.ShowDialog();
                                }
                                if (printPreviewDialog2.Document != null)
                                {
                                    DialogResult result2 = printPreviewDialog2.ShowDialog();
                                }
                                if (printPreviewDialog3.Document != null)
                                {
                                    DialogResult result3 = printPreviewDialog3.ShowDialog();
                                }
                                if (printPreviewDialog1.Document != null)
                                {
                                    DialogResult result4 = printPreviewDialog4.ShowDialog();
                                }
                            }
                            else
                            {
                                if (printPreviewDialog1.Document != null && (!string.IsNullOrEmpty(txt_OneNumber.Text) || !string.IsNullOrEmpty(txt_OneSpecialNumber.Text)))
                                {
                                    printDocument1.Print();
                                    System.Threading.Thread.Sleep(300);
                                }
                                if (printPreviewDialog2.Document != null && (!string.IsNullOrEmpty(txt_ParkAdultNumber.Text) || !string.IsNullOrEmpty(txt_ParkSpecialNumber.Text)))
                                {
                                    printDocument2.Print();
                                    System.Threading.Thread.Sleep(300);
                                }
                                if (printPreviewDialog3.Document != null && (!string.IsNullOrEmpty(txt_TwoNumber.Text)))
                                {
                                    printDocument3.Print();
                                    System.Threading.Thread.Sleep(300);
                                }
                                if (printPreviewDialog4.Document != null && (!string.IsNullOrEmpty(txt_ThreeNumber.Text)))
                                {
                                    printDocument4.Print();
                                    System.Threading.Thread.Sleep(300);
                                }
                            }
                        }
                        _LastPurchaseMoney = txt_PurchaseMoney.Text;
                        _LastSignedNumber = txt_SignedNumber.Text;
                        ResetGuideData();
                        txt_PurchaseMoney.Text = _LastPurchaseMoney;
                        txt_SignedNumber.Text = _LastSignedNumber;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (printPreviewDialog1.Document != null)
            {
                DialogResult result1 = printPreviewDialog1.ShowDialog();
            }
            if (printPreviewDialog2.Document != null)
            {
                DialogResult result2 = printPreviewDialog2.ShowDialog();
            }
            if (printPreviewDialog3.Document != null)
            {
                DialogResult result3 = printPreviewDialog3.ShowDialog();
            }
            if (printPreviewDialog4.Document != null)
            {
                DialogResult result4 = printPreviewDialog4.ShowDialog();
            }
            else if (printPreviewDialog1.Document == null && printPreviewDialog2.Document == null && printPreviewDialog3.Document == null && printPreviewDialog4.Document == null)
            {
                MessageBox.Show("票据信息尚未保存");
            }
        }

        private PrintDoc print(string TicketType, string wharf, System.Drawing.Image img, string saleID, string departmentName, string guide, int people1, int people2, int people3, string operatorName)
        {
            PrintDoc pd = new PrintDoc();            
            Hashtable ht = new Hashtable();
            ht.Add("凭证", TicketType);
            ht.Add("码头", wharf);
            ht.Add("二维码", img);
            ht.Add("票号", saleID);
            ht.Add("社名", departmentName);
            ht.Add("导游", guide);
            ht.Add("进园", people1);
            ht.Add("成人", people2);
            ht.Add("学生", people3);
            ht.Add("开票人", operatorName);
            pd.PrintHash = new Hashtable();
            pd.PrintHash = ht;
            return pd;
        }

        private void save_ticket(string num, int typeid, int saleid)
        {
            if (!string.IsNullOrEmpty(num))
            {
                for (int i = 0; i < int.Parse(num); i++)
                {
                    Tickets t = new Tickets();
                    t.TicketID = Guid.NewGuid();
                    t.TypeID = typeid;
                    t.SaleID = saleid;
                    t.Created_at = DateTime.Now;
                    t.Updated_at = DateTime.Now;
                    tse.Tickets.Add(t);
                    tse.SaveChanges();
                }

            }
        }


        //关联导游信息和旅行社信息
        private void btn_Update_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cBox_GuideCardNum.Text))
            {
                MessageBox.Show("导游信息为空!");
                return;
            }
            else if (string.IsNullOrEmpty(cBox_Department.Text))
            {
                MessageBox.Show("部门信息为空!");
                return;
            }
            else
            {
                int tmp = 0;
                try
                {
                    var guide = tse.Guides.First(u => u.GuideCard == cBox_GuideCardNum.Text);
                    tmp = 1;
                    var depart = tse.Departments.First(u => u.DepartmentName == cBox_Department.Text);
                    tmp = 2;

                    string msg = "";
                    if (checkBox_Connect.Checked)
                    {
                        if (tse.DepartmentsGuidesSet.Where(u => u.GuideID == guide.GuideID && u.DepartmentID == guide.DepartmentID).Count()>0)
                        {
                            MessageBox.Show("该关联已存在！");
                            return;
                        }
                        DepartmentsGuides dg = new DepartmentsGuides();
                        dg.DepartmentID = depart.DepartmentID;
                        dg.GuideID = guide.GuideID;
                        dg.Created_at = DateTime.Now;
                        dg.Updated_at = DateTime.Now;
                        tse.DepartmentsGuidesSet.Add(dg);
                        //guide.DepartmentID = depart.DepartmentID;
                        msg += "已成功将导游：" + guide.Name.Trim() + "关联到：" + depart.DepartmentName.Trim();
                    }
                    if (checkBox_Sign.Checked)
                    {
                        depart.CanSign = 1;
                        msg += "\r\n成功将部门：" + depart.DepartmentName.Trim() + "修改为可签单";
                        txt_SignedPeople.Enabled = true;
                    }
                    else
                    {
                        depart.CanSign = 0;
                        msg += "\r\n成功将部门：" + depart.DepartmentName.Trim() + "修改为不可签单";
                        txt_SignedPeople.Text = "0";
                        txt_SignedPeople.Enabled = false;
                    }
                    tse.SaveChanges();
                    MessageBox.Show(msg);

                }
                catch
                {
                    if (tmp == 0)
                    {
                        MessageBox.Show("导游不存在");
                    }
                    else if (tmp == 1)
                    {
                        MessageBox.Show("部门不存在");
                    }
                    else if (tmp == 2)
                    {
                        MessageBox.Show("修改关联关系失败" + new Exception());
                    }
                    return;
                }
            }
        }
        

        //只允许输入数字
        private void txt_OnlyNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键  
            {
                if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字  
                {
                    e.Handled = true;
                }
            } 
        }
                

        private void cBox_Department_CanSign(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cBox_Department.Text))
            {                
                var depart = tse.Departments.Where(u => u.DepartmentName == cBox_Department.Text.Trim());
                if (depart.Count() > 0)
                {
                    if (depart.FirstOrDefault().CanSign > 0)
                    {
                        checkBox_Sign.Checked = true;
                        txt_SignedPeople.Enabled = true;
                        txt_SignedNumber.Enabled = true;
                    }
                    else
                    {
                        checkBox_Sign.Checked = false;
                        txt_SignedPeople.Enabled = false;
                        txt_SignedNumber.Enabled = false;
                    }
                    _departmentid = depart.FirstOrDefault().DepartmentID;
                }
                else
                    txt_SignedPeople.Enabled = true;
            }
        }

        private void checkBox_Sign_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_Sign.Checked)
            {
                txt_SignedPeople.Enabled = true;
                txt_SignedNumber.Enabled = true;
                int signed = 0;
                if (!string.IsNullOrEmpty(txt_OneNumber.Text))
                {
                    signed += int.Parse(txt_OneNumber.Text);
                    txt_SignedPeople.Text = signed.ToString();
                }
                if (!string.IsNullOrEmpty(txt_OneSpecialNumber.Text)) 
                {
                    signed += int.Parse(txt_OneSpecialNumber.Text);
                    txt_SignedPeople.Text = signed.ToString();
                }
            }
            else
            {
                txt_SignedNumber.Enabled = false;
                txt_SignedPeople.Enabled = false;
                txt_SignedPeople.Text = "";
                txt_SignedNumber.Text = "";
            }
        }

        private void cBox_GuideCardNum_TextChanged(object sender, EventArgs e)
        {
            //if (!string.IsNullOrEmpty(cBox_GuideCardNum.Text))
            //{
            //    ResetTicketData();
            //}
        }

        private void txt_GuidePhone_Leave(object sender, EventArgs e)
        {
            if (lb_GuideNotExist.Visible == false && !string.IsNullOrEmpty(cBox_GuideCardNum.Text))
            {
                var guide = tse.Guides.First(u => u.GuideCard == cBox_GuideCardNum.Text);
                string phone = guide.Phone.Trim();
                if (phone != txt_GuidePhone.Text)
                {
                    guide.Phone = txt_GuidePhone.Text;
                    tse.SaveChanges();
                    MessageBox.Show("检测到您已修改导游手机号为:" + txt_GuidePhone.Text);
                }
            }
        }

        
        private void txt_GuideName_Leave(object sender, EventArgs e)
        {
            if(lb_GuideNotExist.Visible == false && !string.IsNullOrEmpty(cBox_GuideCardNum.Text))
            {
                var guidename = tse.Guides.First(u => u.GuideCard == cBox_GuideCardNum.Text);
                string name = guidename.Name.Trim();
                if(name != txt_GuideName.Text)
                {
                    guidename.Name = txt_GuideName.Text;
                    tse.SaveChanges();
                    MessageBox.Show("检测到您已修改导游姓名为:" + txt_GuideName.Text);
                }
            }
        }

        private void cBox_Sex_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lb_GuideNotExist.Visible == false && !string.IsNullOrEmpty(cBox_GuideCardNum.Text))
            {
                var guidesex = tse.Guides.First(u => u.GuideCard == cBox_GuideCardNum.Text);
                string _sex = guidesex.Sex;
                if (guidesex.Sex != cBox_Sex.Text)
                {
                    guidesex.Sex = cBox_Sex.Text;
                    tse.SaveChanges();
                    MessageBox.Show("检测到您已修改导游性别为:" + cBox_Sex.Text);
                }
            }
        }

        private void txt_DepartPhone_Leave(object sender, EventArgs e)
        {
            if (lb_GuideNotExist.Visible == false && !string.IsNullOrEmpty(cBox_GuideCardNum.Text))
            {

                var departPhone = tse.Departments.FirstOrDefault(u => u.DepartmentName == cBox_Department.Text.Trim());
                string depart = departPhone.ContactNumber;
                if (depart != txt_DepartPhone.Text)
                {
                    departPhone.ContactNumber = txt_DepartPhone.Text;
                    tse.SaveChanges();
                    MessageBox.Show("检测到您已修改旅行社电话为:" + txt_DepartPhone.Text);
                }
            }
        }

        

        

        

     
        
    }
}
